package classloader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
//自定义classload
public class MyTest16 extends ClassLoader {

    private String classLoaderName;

    private String fileExtention = ".class";

    public MyTest16(String classLoaderName) {
        super();//将系统类加载器当作该类的父类加载器
        this.classLoaderName = classLoaderName;
    }

    public MyTest16(ClassLoader pareent, String classLoaderName) {
        super(pareent); //显式指定该类加载器的父加载器
        this.classLoaderName = classLoaderName;
    }

    @Override
    protected Class<?> findClass(String className) {
        System.out.println("findClass,输出这句话说明我们自己的类加载器加载了指定的类");
        System.out.println("class loader name :" + this.classLoaderName);
        byte[] data = this.loadClassData(className);
        return this.defineClass(className, data, 0, data.length);
    }

    private byte[] loadClassData(String name) {
        System.out.println("loadClassData,输出这句话说明我们自己的类加载器 读取磁盘上的class文件");
        InputStream is = null;
        byte[] data = null;
        ByteArrayOutputStream baos = null;
        try {
            this.classLoaderName = this.classLoaderName.replace(".", "/");
            is = new FileInputStream((new File(name + this.fileExtention)));
            baos = new ByteArrayOutputStream();
            int ch = 0;
            while (-1 != (ch = is.read())) {
                baos.write(ch);
            }
            data = baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                baos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return data;
    }

    public static void test(ClassLoader classLoader) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Class<?> clazz = classLoader.loadClass("classloader.MyTest2");
        Object o = clazz.newInstance();
        System.out.println(o);
        System.out.println(o.getClass().getClassLoader());
    }



    public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        MyTest16 myload1 = new MyTest16("load1");
        test(myload1);//根据双亲委托机制，test中的MyTest2 可以由父加载器Launcher$AppClassLoader加载到MyTest2
        //所以  AppClassLoader 为定义类加载器
        // AppClassLoader  和 MyTest16 为初始化加载器


        /*
        可以设置 MyTest16 读取 特定位置的class文件路径，去加载特定位置的文件，就可以实现MyTest16读取类文件，并加载类
        见 MyTest16_1 测试类

         */
    }
}
